<script lang="ts">
	import { goto } from '$app/navigation';
	import { beforeNavigate } from '$app/navigation';
	import { page } from '$app/state';
	import HomePage from '$home/HomePage.svelte';
	import * as jsonLinks from '$lib/data/links.json';
	import { WebState } from '$lib/redux/store.svelte';
	import { latestClientVersion } from '$lib/store';
	import { getValidReleases } from '$lib/types/releases';
	import { UserService, USER_SERVICE } from '$lib/user/userService';
	import { updateFavIcon } from '$lib/utils/faviconUtils';
	import { initTheme } from '$lib/utils/theme.svelte';
	import { provide } from '@gitbutler/core/context';
	import { HttpClient, HTTP_CLIENT } from '@gitbutler/shared/network/httpClient';
	import { PROJECT_SERVICE, ProjectService } from '@gitbutler/shared/organizations/projectService';
	import { APP_STATE } from '@gitbutler/shared/redux/store.svelte';
	import { WebRoutesService, WEB_ROUTES_SERVICE } from '@gitbutler/shared/routing/webRoutes.svelte';
	import { type Snippet } from 'svelte';
	import { readable } from 'svelte/store';
	import { env } from '$env/dynamic/public';
	import '../styles/global.css';
	import '@gitbutler/design-core/core';
	import '@gitbutler/design-core/utility';

	// Initialize theme system
	initTheme();

	interface Props {
		children: Snippet;
	}

	const { children }: Props = $props();

	const routesService = new WebRoutesService('/', true);
	provide(WEB_ROUTES_SERVICE, routesService);

	const TOKEN_STORAGE_KEY = 'AuthService--token';

	/// Temporary cleanup through the migration
	$effect(() => {
		const item = localStorage.getItem(TOKEN_STORAGE_KEY);
		if (item) localStorage.removeItem(TOKEN_STORAGE_KEY);
	});

	const httpClient = new HttpClient(fetch, env.PUBLIC_APP_HOST, readable(undefined), 'include');
	provide(HTTP_CLIENT, httpClient);

	const userService = new UserService(httpClient);
	const user = $derived(userService.user);
	provide(USER_SERVICE, userService);

	const webState = new WebState();
	provide(APP_STATE, webState);

	const projectService = new ProjectService(httpClient, webState.appDispatch);
	provide(PROJECT_SERVICE, projectService);

	// Releases data for changelog
	let releases: any[] = $state([]);

	// Check if current page should use marketing layout
	const isMarketingPage = $derived(
		page.route.id === '/(app)' ||
			page.route.id === '/(app)/home' ||
			page.route.id === '/downloads' ||
			page.route.id === '/nightly' ||
			page.route.id === '/color-generator'
	);

	// Check if current page should render children directly (marketing pages except home)
	const shouldRenderChildren = $derived(
		isMarketingPage && page.route.id !== '/(app)' && page.route.id !== '/(app)/home'
	);

	$effect(() => {
		if (page.url.pathname === '/privacy') {
			window.location.href = jsonLinks.legal.privacyPolicy.url;
		}

		if (!$user && page.route.id === '/(app)/home') {
			goto('/');
		}
	});

	beforeNavigate(() => {
		updateFavIcon(); // reset the icon
	});

	// Fetch latest version and releases when showing marketing page
	$effect(() => {
		if (isMarketingPage) {
			// Fetch latest version
			fetch('https://app.gitbutler.com/api/downloads?limit=1&channel=release')
				.then((response) => response.json())
				.then((data) => {
					const latestReleases = getValidReleases(data);
					if (latestReleases.length > 0) {
						latestClientVersion.set(latestReleases[0].version);
					}
				})
				.catch((error) => {
					console.error('Failed to fetch latest version:', error);
				});

			// Fetch latest 10 releases for changelog
			fetch('https://app.gitbutler.com/api/downloads?limit=10&channel=release')
				.then((response) => response.json())
				.then((data) => {
					releases = getValidReleases(data);
				})
				.catch((error) => {
					console.error('Failed to fetch releases for changelog:', error);
				});
		}
	});
</script>

<svelte:head>
	{#if import.meta.env.MODE !== 'development'}
		<script
			async
			src="https://u.gitbutler.com/script.js"
			data-website-id="c406f339-a2af-4992-9a82-162134323008"
		></script>
	{/if}
</svelte:head>

{#if isMarketingPage}
	<section class="marketing-page">
		{#if shouldRenderChildren}
			{@render children?.()}
		{:else}
			<HomePage {releases} />
		{/if}
	</section>
{:else}
	{@render children?.()}
{/if}

<style lang="postcss">
	.marketing-page {
		display: grid;
		grid-template-columns:
			[full-start]
			repeat(2, 1fr)
			[narrow-start]
			repeat(8, 1fr)
			[narrow-end]
			1fr [off-center] 1fr
			[full-end];
		column-gap: var(--layout-col-gap);
		row-gap: 60px;
		align-items: start;
		width: 100%;
		max-width: 1440px;
		min-height: 100dvh;
		margin: 0 auto;
		padding: 0 var(--layout-side-paddings);

		@media (--desktop-small-viewport) {
			grid-template-columns:
				[full-start]
				1fr
				[narrow-start]
				repeat(10, 1fr)
				[narrow-end off-center]
				1fr
				[full-end];
		}

		@media (--mobile-viewport) {
			grid-template-columns:
				[full-start narrow-start]
				repeat(4, 1fr)
				[narrow-end full-end off-center];
			row-gap: 40px;
		}
	}
</style>
